package models;

import controllers.MonLogger;
import controllers.MonMail;
import grammar.*;
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.ParseTree;

import java.util.Date;


class DescriptiveErrorListener extends BaseErrorListener
{
    public static  requete OWNER ;
    public static DescriptiveErrorListener INSTANCE = new DescriptiveErrorListener();


    @Override
    public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol,
                            int line, int charPositionInLine,
                            String msg, RecognitionException e)
    {

        //String sourceName = recognizer.getInputStream().getSourceName();
       // if (!sourceName.isEmpty()) {
       //     sourceName = String.format("%s:%d:%d: ", sourceName, line, charPositionInLine);
        //}

       // System.err.println(sourceName+ "   l ine "+line+":"+charPositionInLine+" "+msg);
       // System.out.println(" ERREUR TOKEN NOT OK "+msg);
        OWNER.commande = "ERREUR";
        OWNER.information +=  "\n"+      msg;
    }


}



/**
 * Created by richard on 17/06/14.
 */
public class requete {
    public Employe from;
    public Date date;

    public String commande;
    public String information;


    public String toString(){
        return ("# "+
              this.date +" " +
              this.from.adresseMail   +" |" +
               this.commande + "|"


            );

    }

    public void initCmde() {
        DescriptiveErrorListener.OWNER = this;
        information="";
        MonLogger.log("[INIT CMDE] ");
        ANTLRInputStream input = new ANTLRInputStream(commande);

        CommandePatternLexer lexer= new CommandePatternLexer(input);
        lexer.removeErrorListeners();
        lexer.addErrorListener(DescriptiveErrorListener.INSTANCE);
        CommonTokenStream tokens = new CommonTokenStream(lexer);
        CommandePatternParser parser = new CommandePatternParser(tokens);
        parser.Owner = this;

        parser.removeErrorListeners();
        parser.addErrorListener(DescriptiveErrorListener.INSTANCE);

        ParseTree tree = parser.eval();

        System.out.println(this.commande);

       // System.out.println(tree.toStringTree(parser));
    }



    // Traitement de la commande lié à la requéte
    public void startCmde() {

        if (this.commande.equalsIgnoreCase("PING")) {
            MonLogger.log("PING");
            this.cmdePing();
        }
        if (this.commande.equalsIgnoreCase("ERREUR")) {
            MonLogger.log("ERREUR");
            MonMail.sendMailText(this.from.adresseMail, this.commande, this.information);
        }


    }


    // Ici on reçoit ping on envoie pong
    private void cmdePing() {
        MonMail.sendMailText(this.from.adresseMail, "PONG","PONG");
    }
}
